
<script type="text/x-red" data-template-name="link in">
    <div class="form-row">
        <label for="node-input-name"><i class="fa fa-tag"></i> <span data-i18n="common.label.name"></span></label>
        <input type="text" id="node-input-name" data-i18n="[placeholder]common.label.name">
    </div>
    <div class="form-row node-input-link-row"></div>
</script>
<script type="text/x-red" data-template-name="link out">
    <div class="form-row">
        <label for="node-input-name"><i class="fa fa-tag"></i> <span data-i18n="common.label.name"></span></label>
        <input type="text" id="node-input-name" data-i18n="[placeholder]common.label.name">
    </div>
    <div class="form-row node-input-link-row"></div>
</script>

<script type="text/text">
(function() {

    var treeList;

    function onEditPrepare(node,targetType) {
        if (!node.links) {
            node.links = [];
        }
        node.oldLinks = [];

        var activeSubflow = RED.nodes.subflow(node.z);

        treeList = $("<div>")
            .css({width: "100%", height: "100%"})
            .appendTo(".node-input-link-row")
            .treeList({})
            .on('treelistitemmouseover',function(e,item) {
                if (item.node) {
                    item.node.highlighted = true;
                    item.node.dirty = true;
                    RED.view.redraw();
                }
            })
            .on('treelistitemmouseout',function(e,item) {
                if (item.node) {
                    item.node.highlighted = false;
                    item.node.dirty = true;
                    RED.view.redraw();
                }
            });
        var candidateNodes = RED.nodes.filterNodes({type:targetType});

        var flows = [];
        var flowMap = {};

        if (activeSubflow) {
            flowMap[activeSubflow.id] = {
                id: activeSubflow.id,
                class: 'red-ui-palette-header',
                label:  "Subflow : "+(activeSubflow.name || activeSubflow.id),
                expanded: true,
                children: []
            };
            flows.push(flowMap[activeSubflow.id])
        } else {
            RED.nodes.eachWorkspace(function(ws) {
                flowMap[ws.id] = {
                    id: ws.id,
                    class: 'red-ui-palette-header',
                    label: (ws.label || ws.id)+(node.z===ws.id ? " *":""),
                    expanded: true,
                    children: []
                }
                flows.push(flowMap[ws.id])
            })
        }

        candidateNodes.forEach(function(n) {
            if (flowMap[n.z]) {
                var isChecked = false;
                isChecked = (node.links.indexOf(n.id) !== -1) || (n.links||[]).indexOf(node.id) !== -1;
                if (isChecked) {
                    node.oldLinks.push(n.id);
                }
                flowMap[n.z].children.push({
                    id: n.id,
                    node: n,
                    label: n.name||n.id,
                    selected: isChecked
                })
            }
        });
        flows = flows.filter(function(f) { return f.children.length > 0 })
        treeList.treeList('data',flows);
        setTimeout(function() {
            treeList.treeList('show',node.z);
        },100);
    }

    function resizeNodeList() {
        var rows = $("#dialog-form>div:not(.node-input-link-row)");
        var height = $("#dialog-form").height();
        for (var i=0;i<rows.length;i++) {
            height -= $(rows[i]).outerHeight(true);
        }
        var editorRow = $("#dialog-form>div.node-input-link-row");
        height -= (parseInt(editorRow.css("marginTop"))+parseInt(editorRow.css("marginBottom")));
        $(".node-input-link-row").css("height",height+"px");
    }

    function onEditSave(node) {
        var flows = treeList.treeList('data');
        node.links = [];
        flows.forEach(function(f) {
            f.children.forEach(function(n) {
                if (n.selected) {
                    node.links.push(n.id);
                }
            })
        })
        node.oldLinks.sort();
        node.links.sort();
        var nodeMap = {};
        var length = Math.max(node.oldLinks.length,node.links.length);
        for (var i=0;i<length;i++) {
            if (i<node.oldLinks.length) {
                nodeMap[node.oldLinks[i]] = nodeMap[node.oldLinks[i]]||{};
                nodeMap[node.oldLinks[i]].old = true;
            }
            if (i<node.links.length) {
                nodeMap[node.links[i]] = nodeMap[node.links[i]]||{};
                nodeMap[node.links[i]].new = true;
            }
        }
        var n;
        for (var id in nodeMap) {
            if (nodeMap.hasOwnProperty(id)) {
                n = RED.nodes.node(id);
                if (n) {
                    if (nodeMap[id].old && !nodeMap[id].new) {
                        // Removed id
                        i = n.links.indexOf(node.id);
                        if (i > -1) {
                            n.links.splice(i,1);
                        }
                    } else if (!nodeMap[id].old && nodeMap[id].new) {
                        // Added id
                        i = n.links.indexOf(id);
                        if (i === -1) {
                            n.links.push(node.id);
                        }
                    }
                }
            }
        }
    }

    function onAdd() {
        for (var i=0;i<this.links.length;i++) {
            var n = RED.nodes.node(this.links[i]);
            if (n && n.links.indexOf(this.id) === -1) {
                n.links.push(this.id);
            }
        }
    }

    RED.nodes.registerType('link in',{
        category: 'common',
        color:"#ddd",//"#87D8CF",
        defaults: {
            name: {value:""},
            links: { value: [] }
        },
        inputs:0,
        outputs:1,
        icon: "link-out.svg",
        outputLabels: function(i) {
            return this.name||this._("link.linkIn");
        },
        label: function() {
            return this.name||this._("link.linkIn");
        },
        labelStyle: function() {
            return this.name?"node_label_italic":"";
        },
        oneditprepare: function() {
            onEditPrepare(this,"link out");
        },
        oneditsave: function() {
            onEditSave(this);
        },
        onadd: onAdd,
        oneditresize: resizeNodeList
    });

    RED.nodes.registerType('link out',{
        category: 'common',
        color:"#ddd",//"#87D8CF",
        defaults: {
            name: {value:""},
            links: { value: []}
        },
        align:"right",
        inputs:1,
        outputs:0,
        icon: "link-out.svg",
        inputLabels: function(i) {
            return this.name||this._("link.linkOut");
        },
        label: function() {
            return this.name||this._("link.linkOut");
        },
        labelStyle: function() {
            return this.name?"node_label_italic":"";
        },
        oneditprepare: function() {
            onEditPrepare(this,"link in");
        },
        oneditsave: function() {
            onEditSave(this);
        },
        onadd: onAdd,
        oneditresize: resizeNodeList
    });
})();
</script>
